/**
 * SecurityFilter.java
 */

package us.gaaoc.framework.webapp.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import us.gaaoc.framework.model.Person;


/**
 * This class we are not using. To filter the user we use the SecurityPhaseListener
 * rather than this class.
 * 
 * 
 * This is the first security filter than gets called after the login page.
 *<br>
 * Invalid users are redirected to index page
 * <p>Copyright: Copyright (c) 2005</p>
 * <p>Company: GAAOC</p>
 *
 * @version Beta 0.9
 *
 *
 */
public class SecurityFilter
    implements Filter {
  /**/
  public SecurityFilter() {
  }

  /**/
  public void init(FilterConfig filterConfig) throws ServletException {
  }

  /**
   *
   * @param request ServletRequest
   * @param response ServletResponse
   * @param chain FilterChain
   * @throws IOException
   * @throws ServletException
   *
   * <br><br>
   * Note: Browser cache-Control is add to the response here.
   */
  public void doFilter(ServletRequest request, ServletResponse response,
                       FilterChain chain) throws IOException, ServletException {

    if (request != null) {
      HttpServletRequest httpRequest = (HttpServletRequest) request;
      HttpServletResponse httpResponse = (HttpServletResponse) response;
      HttpSession session = httpRequest.getSession();

      Person person = (Person) session.getAttribute("person");
      //used to keep the browser from caching pages
      if (person != null) {
        httpResponse.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");
        httpResponse.setHeader("Cache-Control",
                               "no-store, no-cache, must-revalidate");
        httpResponse.addHeader("Cache-Control", "post-check=0, pre-check=0");
        httpResponse.setHeader("Pragma", "no-cache");
        chain.doFilter(httpRequest, httpResponse);
      }
      else {
        session.invalidate();
        httpResponse.sendRedirect(httpRequest.getContextPath() + "/index.html");
      }
    }
  }

  public void destroy() {

  }
}
